package com.hjy.common.utils;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.hjy.common.enumeration.RpcError;
import com.hjy.common.exception.RpcException;

import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class NacosUtils {
    /**
     * nacos 对象
     */
    private static final NamingService namingService;
    /**
     * 服务名
     */
    private static final Set<String> serviceNames = new HashSet<>();
    private static InetSocketAddress address;

    private static final String SERVER_ADDR = "127.0.0.1:8848";

    static {
        namingService = getNacosNamingService();
    }

    /**
     * 获取 nacos 对象
     * @return nacos 对象
     */
    public static NamingService getNacosNamingService() {
        try {
            return NamingFactory.createNamingService(SERVER_ADDR);
        } catch (NacosException e) {
            System.err.println("连接到Nacos时有错误发生: " + e.getErrMsg());
            throw new RpcException(RpcError.FAILED_TO_CONNECT_TO_SERVICE_REGISTRY);
        }
    }

    /**
     * 注销与nacos的绑定
     */
    public static void clearRegistry() {
        if (!serviceNames.isEmpty() && address != null) {
            String host = address.getHostName();
            int port = address.getPort();
            Iterator<String> iterator = serviceNames.iterator();
            while (iterator.hasNext()) {
                String serviceName = iterator.next();
                // 注销与nacos的注册
                try {
                    namingService.deregisterInstance(serviceName, host, port);
                } catch (NacosException e) {
                    System.err.println("注销服务" + serviceName + "失败!!!");
                }
            }
        }
    }
}
